package com.hxci.zc.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.hxci.zc.domain.Dept;
import com.hxci.zc.domain.User;
import com.hxci.zc.service.DeptService;
import com.hxci.zc.service.UserService;
import com.hxci.zc.util.PageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("user")
public class UserController {
    @Autowired
    DeptService deptService;
    @Autowired
    UserService userService;

     @RequestMapping("preadd")
     public String preadd(Model model){
        List<Dept> dlist = deptService.list();
        model.addAttribute("dlist",dlist);
        return "jsp/user_create";
     }

    @RequestMapping("add")
    public String preadd(User user){
        userService.saveOrUpdate(user);
        return "redirect:/user/query";
    }

    @RequestMapping("query")
    public String query(Model model,@RequestParam Map<String, Object> params){
        String name = (String)params.get("name");
        PageUtils page= userService.queryPage(params);
//        List<User> ulist = userService.list(new QueryWrapper<User>().like(StringUtils.isNotBlank(name),"name",name));
//
//        for (User user: ulist) {
//            Dept dept = deptService.getById(user.getBid());
//            user.setBname(dept.getDname());
//        }
       model.addAttribute("name",name);
       model.addAttribute("ul",page);
        return "jsp/user_index";
    }

    @RequestMapping("del")
    public String del(User  user){
        //userService.removeById(id);//物理删除
        user.setStatus(0);
        userService.updateById(user);//逻辑删除
        return "redirect:/user/query";
    }
    @RequestMapping("dels")
    public String dels(@RequestParam(value = "ids",required = false) String  ids){
        String[] arr =ids.split(",");
        List<User> users = new ArrayList<User>();
        for (String id:arr) {
            User u = new User();
            u.setId(Integer.valueOf(id));
            u.setStatus(0);
            users.add(u);
        }

       // userService.removeByIds(is);//物理删除
        userService.updateBatchById(users);//逻辑删除，批量修改
        return "redirect:/user/query";
    }

    @RequestMapping("edit")
    public String edit(Integer  id,Model model){
        User user = userService.getById(id);
        List<Dept> dlist = deptService.list();
        model.addAttribute("dlist",dlist);
        model.addAttribute("u",user);
        return "jsp/user_create";
    }
}
